const db = require("../db/index")
const jwt = require("jsonwebtoken")
const {secretKey,expiresIn} = require("../config/index")
const {formatDateTime} = require("../tools/dateFormat")
const slat = "[CYW(HJH)M<Y>]"

const axios = require("axios");
const b_api_key = "vsOY4TFkG7K9UT9zr6DDAPqt";
const b_secret_key = "aYMO1eyRn9NNAKYL8eBymsfIETQUqtm4";
const qs = require("qs")
const { url } = require("inspector")

exports.canJoinSocial = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    console.log("用户上传社交数据",userInfo)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,async (err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        const sql = "SELECT * FROM user WHERE userId = ?"
        db.query(sql,data.userId, (err,results) => {
            console.log(err,results,"插入用户烟友圈数据")
            if (err) {
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
           if (results.length == 0) {
                return res.send({ status: 500, message: "未找到用户" })
           }
           const userData = results[0]
           if (userData.social == "0") { //非违规用户
            // 1->正常使用
            // 非1 停用烟友圈
            res.send({
                status:200,
                code:1
            })
           } else {
            res.send({
                status:200,
                code:2 //违规用户
            })
           }
        })
        
    })
}

//用户上传朋友圈
exports.sendUserSocial = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    console.log("用户上传社交数据",userInfo)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,async (err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(data,'jwt解析')
        // const wordRes = await checkUserWords(userInfo.words,data.userId)
        // console.log("百度敏感词鉴定res",wordRes)
       
        
        const sql = "SELECT * FROM user WHERE userId = ?"
        db.query(sql,data.userId, (err,results) => {
            if (err) {
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
           if (results.length == 0) {
                return res.send({ status: 500, message: "未找到用户" })
           }
           const userData = results[0]
           
           let insertData = {
            userId:data,
            imgs:userInfo.imgs.join(slat),
            words:userInfo.words,
            name:userData.name,
            lat:userData.lat,
            lng:userData.lng,
            createDate:formatDateTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
            userImage:userData.userImage,
            socialId:userInfo.socialId,
            type:userInfo.type
           }
           console.log("用户社交入参",insertData)
           const sqlSocial = "INSERT INTO social SET ?";
           db.query(sqlSocial,insertData,(err,results) => {
            //执行SQL失败
            console.log("插入用户社交表",err,results)
            if (err) return res.send({status:500,message:"上传失败"})
            // if (results.affectedRows !== 1) {
            //     return res.send({ status: 500, message: "上传失败" });
            // }
            res.send({status:200,message:'上传成功!',code:1})
        })
        })
    })
}

//获取社交列表
exports.getSocials = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    console.log("获取社交列表",userInfo)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        let {page,size} = userInfo
        console.log(data,'jwt解析')
        const sql = `SELECT * FROM social ORDER BY createDate DESC LIMIT ${size} OFFSET ${(page - 1) * size}`
        db.query(sql,async (err,results) => {
            
            if (err) return res.send({status:500,message:"获取列表失败"})
            // if (results.affectedRows !== 1) {
            //     return res.send({ status: 500, message: "获取列表失败" });
            // }
            let obj = []
            const likeSQL = "SELECT * FROM likeHistory WHERE socialId = ?"
            const commentSQL = "SELECT * FROM comment WHERE socialId = ?"
            for(let i = 0; i < results.length;i++) {
                let item = results[i]
                const temp = await queryDatabase(likeSQL,item.socialId)
                const commentTemp = await queryDatabase(commentSQL,item.socialId)
                const showValue = {
                    ...item,
                    imgs:item.imgs.length > 0 ? item.imgs.split(slat) : [],
                    likeCount:temp.length ?? 0,
                    commentCount:commentTemp.length ?? 0,
                    createDate:item.createDate.substring(5,item.createDate.length - 3)
                }
                obj.push(showValue)
            }
            console.log(obj,'社交列表sql回调')
            res.send({status:200,message:'获取列表成功!',data:obj})
        })
    })
}

async function queryDatabase(sql, params) {  
    return new Promise((resolve, reject) => {  
      // 假设你有一个名为db的数据库连接对象  
      db.query(sql, params, (error, results) => {  
        if (error) {  
          reject(error);  
        } else {  
          resolve(results);  
        }  
      });  
    });  
  }

  async function performQueries(queries) {  
    const results = [];  
    for (const [sql, params] of queries) {  
      try {  
        const result = await queryDatabase(sql, params);  
        results.push(result);  
      } catch (error) {  
        console.error('An error occurred:', error);  
      }  
    }  
    return results;  
  }  
    

// 百度对敏感词的鉴定
//获取百度token
const getBDToken = async () => {
    return new Promise((resolve, reject) => {
      axios
        .post(
          `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${b_api_key}&client_secret=${b_secret_key}`
        )
        .then((res) => {
          console.log(res, "百度token获取成功");
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
          console.log(err, "百度token获取失败");
        });
    });
  };

exports.checkUserWords = (req,res) => {
    // return new Promise(async (resolve,reject) => {
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    console.log("检测用户敏感词",userInfo)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,async (err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        const bd_token = (await getBDToken()).access_token;
        const sendData = {
            text:userInfo.words,
            userId:data.userId
        }
        console.log("百度发送data",sendData)
        axios({
            url:`https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=${bd_token}`,
            data:qs.stringify(sendData),
            method:"POST",
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded' 
            }
        }).then(wordRes => {
            console.log(wordRes.data,'百度answer成功')
            if (wordRes.data.conclusion != "合规") {
                res.send({
                    status:200,
                    message:"发布失败，文本中包含不合规信息",
                    code:0
                })
                return
            }
            res.send({status:200,message:'合规!',code:1})
        }).catch(err => {
            console.log(err,'百度answer失败')
            res.send({status:500,message:'错误!',code:0})
        });
    })
}



//点赞
exports.likeSocial = (req,res) => {
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    console.log("点赞移动端入参",userInfo)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,async (err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        const {socialId,likeId} = userInfo
        const sql = `SELECT * FROM likeHistory WHERE socialId = ? AND userId = ?`
        db.query(sql,[socialId,data.userId],(err,results) => {
            //执行SQL失败
            console.log("点赞操作sql",results,err)
            if (err) return res.send({status:0,message:"操作失败"})
            if (results.length > 0) {
                return res.send({status:0,message:'您已经点赞过'})
            }
            const insertSQL = "INSERT INTO likeHistory SET ?"
            const likeData = {
                socialId,
                userId:data.userId,
                likeId
            }
            db.query(insertSQL,likeData,(err,results) => {
                if (err) return res.send({status:0,message:"操作失败"})
                return res.send({status:1,message:"点赞成功"})
            })
        })

    })
}

//发布评论
exports.publishComment = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    console.log("发布评论",userInfo)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        const userSQL = `SELECT * FROM user WHERE userId = ?`
        db.query(userSQL,data.userId,(err,userRes) => {
            if (err) {
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(userRes,'sql results')
           if (userRes.length == 0) {
                return res.send({ status: 500, message: "未找到用户" })
           }
           const {name,userImage} = userRes[0]
           const inserData = {
                name,
                userImage,
                createDate:formatDateTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
                socialId:userInfo.socialId,
                content:userInfo.content,
                commentId:userInfo.commentId,
                userId:data.userId,
                isDelete:0
           }
           const commentSQL = `INSERT INTO comment SET ?`
           db.query(commentSQL,inserData,(commentErr,commentRes) => {
            console.log("用户评论",commentErr,commentRes)
            if (commentErr) return res.send({status:500,message:"上传失败"})
            // if (results.affectedRows !== 1) {
            //     return res.send({ status: 500, message: "上传失败" });
            // }
            res.send({status:200,message:'已发布!',code:1})
           })

        })
    })
}

//获取评论列表
exports.getCommentList = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    console.log("获取评论列表",userInfo)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }

        const sql = `SELECT * FROM comment WHERE socialId = ? ORDER BY createDate DESC`
        db.query(sql,userInfo.socialId,async (err,results) => {
            if (err) return res.send({status:500,message:"获取列表失败"})
            res.send({
                status: 200,
                message: "获取评论列表成功",
                data: results.map(item => {
                    return {
                        ...item,
                        createDate:item.createDate.substring(5,item.createDate.length - 3)
                    }
                }),
            });
        })
    })
}